﻿using System;
using System.Diagnostics;
using System.IO;
using DetailManager.BusinessLogic;
using Tekla.Structures.Extensions.Basics;

namespace DetailManager.Tools
{
    //Source for some of code from: http://olondono.blogspot.com/2008/01/about-trace-listeners.html
    public class LogListener
    {
        private const string TraceLogFileName = "TraceLog.txt";
        private static TextWriterTraceListener _listener;

        private static string LogFileRootPath
        {
            get { return AppLogic.AppDataFolder; }
        }

        private static FileInfo TraceLogFile
        {
            get { return new FileInfo(System.IO.Path.Combine(LogFileRootPath, TraceLogFileName)); }
        }

        public TextWriterTraceListener Listener { get { return _listener; } }

        public static void OpenFileInSeperateProcess()
        {
            _listener.Flush();
            System.Diagnostics.Process.Start(TraceLogFile.FullName);
        }

        public LogListener()
        {
            // Second step: create some trace listeners
            _listener = new TextWriterTraceListener(TraceLogFile.FullName);

            // Configuring trace listeners
            _listener.TraceOutputOptions = TraceOptions.DateTime | TraceOptions.Timestamp | TraceOptions.Callstack;

            // Adding our trace listeners
            Trace.Listeners.Add(_listener);
            Trace.AutoFlush = true;

            //Adding debug listeners
            //Debug.Listeners.Add(_listener);
            //Debug.AutoFlush = true;

            WriteStartupInfo();
        }

        private static void WriteStartupInfo()
        {
            Trace.WriteLine("Log file started: " + DateTime.Now);
            Trace.WriteLine("Trace file Initialized at: " + TraceLogFile.FullName);
            Trace.WriteLine("Assembly build name: " + AppInfo.ApplicationName);
            Trace.WriteLine("Assembly version: " + AppInfo.AssemblyVersion);
            Trace.WriteLine("Assembly build date: " + AppInfo.RetrieveLinkerTimestamp());
            Trace.WriteLine("-------------------------------------------------------------------");
        }

        public void CloseLog()
        {
            Trace.WriteLine("Log file closed: " + DateTime.Now);
            Trace.WriteLine("-------------------------------------------------------------------");
            Trace.WriteLine(System.Environment.NewLine);
            _listener.Close();
        }
    }
}